﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Taxhui.Utils.UserModel;

namespace Taxhui.Utils.HttpUtils
{
    public static class Http
    {
        public static RetModel Request(string address, string method, object param)
        {
            try
            {
                RetModel rm = new RetModel() { ErrCode = "0", Success = false };
                if (string.IsNullOrEmpty(method))
                    method = "GET";
                else
                    method = method.ToUpper();
                //Http请求对象
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(address));
                webRequest.Method = method;
                //设置返回类型为json
                webRequest.Accept = "application/json";
                webRequest.ContentType = "application/json; charset = utf-8";
                string data = "";
                if (param != null)
                    data = param.ToString();
                if ("" == data)
                {
                    webRequest.ContentLength = 0;
                }
                else
                {    
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(webRequest.GetRequestStream());
                    sw.Write(data);
                    sw.Flush();
                    sw.Close();
                    sw = null;
                }
                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream());
                string retstr = sr.ReadToEnd();
                sr.Close();
                sr = null;
                HttpStatusCode status = webResponse.StatusCode;
                string err = webResponse.StatusDescription;
                if ("OK" == status.ToString())
                {
                    rm.Success = true;
                    rm.ErrCode = "0";
                    rm.Data = retstr;
                    return rm;
                }
                else
                {
                    rm.Success = false;
                    rm.ErrCode = ((int)status).ToString();
                    rm.ErrInfo = err;
                    return rm;
                }
            }
            catch (Exception ex)
            {
                return new RetModel() { ErrCode = "9999", ErrInfo = ex.Message, Success = false };
            }
        }
    }
}
